package com.smart.sso.server.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smart.mvc.service.mybatis.impl.ServiceImpl;
import com.smart.sso.server.dao.DeptDao;
import com.smart.sso.server.model.Dept;
import com.smart.sso.server.service.DeptService;

@Service("deptService")
public class DeptServiceImpl extends ServiceImpl<DeptDao, Dept, Integer> implements DeptService {

	@Resource
	private DeptService deptService;

	@Autowired
	public void setDao(DeptDao dao) {
		this.dao = dao;
	}

	public void save(Dept t) {
		super.save(t);
	}

	public List<Dept> findByName(String name, Boolean isEnable) {
		return dao.findByName(name, isEnable);
	}

	@Transactional
	public void deleteDept(Integer id) {
		List<Integer> idList = new ArrayList<Integer>();

		List<Dept> list = deptService.findByName(null, null);
		loopSubList(id, idList, list);
		idList.add(id);

		verifyRows(dao.deleteById(idList), idList.size(), "权限数据库删除失败");
	}

	// 递归方法，删除子权限
	protected void loopSubList(Integer id, List<Integer> idList, List<Dept> list) {
		for (Dept p : list) {
			if (id.equals(p.getParentId())) {
				idList.add(p.getId());
				loopSubList(p.getId(), idList, list);
			}
		}
	}
}
